/*
 * util.cpp
 *
 *  Created on: Feb 28, 2015
 *      Author: burek
 */

#include "../rascal-conf.h"

int rsl_parseUTF8(uint8_t * srcBytes, rchar * dstChars, int maxSrc)
{
	int length = 0;
	int srcLen = 0;
	static uint8_t mask[] = {192, 224, 240};

	for(int b = 0; b < maxSrc; ++b)
	{
		/* mask values for bit pattern of first byte in multi-byte
		 UTF-8 sequences:
		   192 - 110xxxxx - for U+0080 to U+07FF
		   224 - 1110xxxx - for U+0800 to U+FFFF
		   240 - 11110xxx - for U+010000 to U+1FFFFF */

		unsigned short i, j;

		if(*srcBytes == 0 || srcLen >= maxSrc)
		{
			*dstChars = 0;
			return length;
		}

		i = 0;
		if ((srcBytes[0] & mask[0]) == mask[0]) i++;
		if ((srcBytes[0] & mask[1]) == mask[1]) i++;
		if ((srcBytes[0] & mask[2]) == mask[2]) i++;

		if(i == 0)
		{
			*dstChars = (rchar)srcBytes[0];
			srcBytes++;
			srcLen++;

			dstChars++;
			length++;
		}
		else if(i == 1)
		{
			*dstChars = (((rchar)srcBytes[0] & 0x1F) << 6);
			srcBytes++;
			srcLen++;

			if(srcLen >= maxSrc) return -1;

			*dstChars |= ((rchar)srcBytes[0] & 0xF);
			srcBytes++;
			srcLen++;

			dstChars++;
			length++;
		}
		else if(i == 2)
		{
			*dstChars = (((rchar)srcBytes[0] & 0x1F) << 12);
			srcBytes++;
			srcLen++;

			if(srcLen >= maxSrc) return -1;

			*dstChars |= ((rchar)srcBytes[0] & 0xF) << 6;
			srcBytes++;
			srcLen++;

			if(srcLen >= maxSrc) return -1;

			*dstChars |= ((rchar)srcBytes[0] & 0xF);
			srcBytes++;
			srcLen++;

			dstChars++;
			length++;
		}
		else if(i == 3)
		{
			return -1;
		}
	}
	*dstChars = 0;
	return length;
}

int rsl_nextCharPos(const rchar * text, rchar c, int maxLen)
{
	int n = 0;
	while(n < maxLen && *text != 0)
	{
		if(*text == c)
			return n;
		n++;
		text++;
	}
	return -1;
}

int rsl_skipBlanks(const rchar * text, int maxLen)
{
	int n = 0;
	while(n < maxLen && *text != 0)
	{
		if(*text != ' ' && *text != '\t' && *text != '\n' && *text != '\r')
			return n;
		n++;
		text++;
	}
	return -1;
}
